package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"goTestToMod/viper_test/config"
)

func GetEnvInfo (key string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(key)
}

func main(){
	isDebug := GetEnvInfo("DEBUG")
	configPrefix := "config"
	configFileName := fmt.Sprintf("viper_test/%s-pro.yaml", configPrefix)
	if isDebug {
		configFileName = fmt.Sprintf("viper_test/%s-debug.yaml", configPrefix)
	}

	v := viper.New()
	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}

	cfg := config.GlobalServerCfg
	if err := v.Unmarshal(&cfg); err != nil{
		panic(err)
	}

	fmt.Printf("读取配置成功！ 配置信息： %v", cfg)

	// 动态加载
	v.WatchConfig()
	v.OnConfigChange(func (e fsnotify.Event){
		fmt.Println("配置发生变化", e.Name)
		_ = v.ReadInConfig()
		_ = v.Unmarshal(&cfg)
		fmt.Println("配置信息", cfg)
	})
}


